import { createRouter, createWebHashHistory, createWebHistory } from "vue-router"
import staticRoutes from "./staticRoutes"
import { useUserStore } from "@/store/modules/user"
import { useAuthStore } from "@/store/modules/auth"
import { whiteList } from "@/config/white-list"
import { getToken } from "@/utils/storage/cookies"
import NProgress from "nprogress"
import "nprogress/nprogress.css"

const router = createRouter({
  history:
    import.meta.env.VITE_ROUTER_HISTORY === "hash"
      ? createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH)
      : createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
  routes: staticRoutes
})

NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  if (getToken()) {
    if (to.path === "/login") {
      next({ path: "/" })
    } else {
      next()
    }
  } else {
    if (to.path === "/login") {
      next()
    } else {
      next("/login")
    }
  }
  NProgress.done()
})

router.afterEach(() => {
  NProgress.done()
})

export default router
